from zope.interface import Interface
from zope.interface import implements
from plone.memoize.instance import memoize
from zope.i18n.interfaces import ITranslationDomain
from zope.component import queryUtility
from zope.component import getMultiAdapter

from plone.app.portlets.portlets import base
from plone.portlets.interfaces import IPortletDataProvider

from zope import schema
from zope.formlib import form
from Products.Five.browser.pagetemplatefile import ViewPageTemplateFile

from plone.portlet.collection.collection import ICollectionPortlet
from plone.portlet.collection.collection import Assignment as baseAssignment
from plone.portlet.collection.collection import Renderer as baseRenderer

from my315ok.fangcan import fangcanMessageFactory as _
from my315ok.products import productsMessageFactory as _a
from my315ok.portlet.rollitems import RollPortletMessageFactory as _r

class IrecommendHousePortlet(ICollectionPortlet):
    """A portlet

    It inherits from IPortletDataProvider because for this portlet, the
    data that is being rendered and the portlet assignment itself are the
    same.
    """

    # TODO: Add any zope.schema fields here to capture portlet configuration
    # information. Alternatively, if there are no settings, leave this as an
    # empty interface - see also notes around the add form and edit form
    # below.

    # some_field = schema.TextLine(title=_(u"Some field"),
    #                              description=_(u"A field to use"),
    #                              required=True)
    topid = schema.TextLine(title=_r(u"top id"),
                             description=_r(u"the wraped top id of the roll zone"),
                             required=True)
    cssid = schema.TextLine(title=_r(u"css id"),
                             description=_r(u"the css id of the roll zone"),
                             required=True)
    previewmode = schema.Choice(
        title=_a(u"image size"),
        description=_a(u"Choose source image size"),
        required = True,
        default = "thumb",       
        vocabulary = 'product.ImageSizeVocabulary' )
    roll_direc = schema.Choice(
        title=_r(u"direction"),
        description=_r(u"Choose the roll direction"),
        vocabulary = 'rollitems.RollDirectionVocabulary' )
    
    speed = schema.Int(title=_r(u"speed"),
                       description=_r(u"Specify the speed of the roll items "),                                      
                       required=True)
    pause = schema.Int(title=_r(u"pause time"),
                       description=_r(u"Specify the time of pause(ms)"),
                       required=True)
    step = schema.Int(title=_r(u"step length"),
                       description=_r(u"Specify the step length of every move."),
                       required=True)


class Assignment(base.Assignment):
    """Portlet assignment.

    This is what is actually managed through the portlets UI and associated
    with columns.
    """

    implements(IrecommendHousePortlet)

    # TODO: Set default values for the configurable parameters here

    header = u""
    target_collection=None
    limit = None
    random = False
    show_more = True
    show_dates = False
    crop_title = False
    wordsnum = 6
    topid = u""
    cssid = u""
    previewmode = "mini"
    roll_direc = "up"
    speed = 30
    pause = 1000
    step = 1

    def __init__(self, header=u"", target_collection=None, limit=None, random=False, show_more=True, \
                 show_dates=False,crop_title=False,wordsnum=6,topid=u"",cssid=u"",previewmode="mini",\
                 roll_direc="up",speed="30",pause=1000,step=1):
        self.header = header
        self.target_collection = target_collection
        self.limit = limit
        self.random = random
        self.show_more = show_more
        self.show_dates = show_dates
        self.crop_title = crop_title
        self.wordsnum = wordsnum
        self.topid = topid
        self.cssid = cssid
        self.previewmode = previewmode
        self.roll_direc = roll_direc
        self.speed = speed
        self.pause = pause
        self.step = step
       

    @property
    def title(self):
        """This property is used to give the title of the portlet in the
        "manage portlets" screen.
        """
        return _(u"RecommentHousePortlet")


class Renderer(baseRenderer):
    """Portlet renderer.

    This is registered in configure.zcml. The referenced page template is
    rendered, and the implicit variable 'view' will refer to an instance
    of this class. Other methods can be added and referenced in the template.
    """

    render = ViewPageTemplateFile('recommendhouseportlet.pt')
    
    @memoize
    def img_tag(self,bn):
        try:
            scale = self.data.previewmode
        except:
            scale = "preview"
        
        url = bn.getURL()
        tl = bn.Title
        if scale == "original":
            imgurl = url + "/image"
        else:
            imgurl = url + "/image_" + scale
        portal_state = getMultiAdapter((self.context, self.request), name=u'plone_portal_state')
        portal = portal_state.portal()
        p_url = portal.absolute_url()
        existimg = portal.unrestrictedTraverse(imgurl, default=None)
        if existimg == None:
            imgurl = p_url + "/++resource++fcwatermark_%s.jpg" % scale 
#        imgtag ="<img src ='%s' alt='%s'/>" % (url,tl)
        imgtag = "<img src='%s' alt='%s' />" %(imgurl,tl)
        return imgtag
    @memoize
    def translates(self,item):
#        import pdb
#        pdb.set_trace()      
        
        util = queryUtility(ITranslationDomain, 'my315ok.fangcan')    
        tted = util.translate(item,target_language="zh",
                                       default="yuhu")           
        return tted

    
    @memoize   
    def main_parameters(self):
#        import pdb
#        pdb.set_trace()
        bns = self.results()
#        ln = self.data.wordsnum
        re = []
        item = {}
        for bs in bns:
            name = bs.Area
            name = self.translates(name)
            item['title'] = self.cropTitle(bs.Title)
            item['url'] = bs.getURL()
            item['unitprice'] = bs.Sale_unitprice
            item['area'] = name
            item['imgtag'] = self.img_tag(bs)
            re.append(item)
            item = {}
            
        return re
    
    @memoize
    def render_marqueejs(self):      
        cssid = self.data.cssid
       
        out="""jq(document).ready(function(){
        rolltext(".%(mid)s");    
});""" % dict(mid=cssid)
        return out   


# NOTE: If this portlet does not have any configurable parameters, you can
# inherit from NullAddForm and remove the form_fields variable.


class AddForm(base.AddForm):
    """Portlet add form.

    This is registered in configure.zcml. The form_fields variable tells
    zope.formlib which fields to display. The create() method actually
    constructs the assignment that is being added.
    """
    form_fields = form.Fields(IrecommendHousePortlet)

    def create(self, data):
        return Assignment(**data)


# NOTE: IF this portlet does not have any configurable parameters, you can
# remove this class definition and delete the editview attribute from the
# <plone:portlet /> registration in configure.zcml

class EditForm(base.EditForm):
    """Portlet edit form.

    This is registered with configure.zcml. The form_fields variable tells
    zope.formlib which fields to display.
    """
    form_fields = form.Fields(IrecommendHousePortlet)
